package com.yc.mvc.web;

import org.springframework.core.convert.converter.Converter;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/5/4
 * Email haijunzhou@hnit.edu.cn
 */
public class TimestampConvertor implements Converter<String,Timestamp> {
    SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Timestamp convert(String source) {
        // yyyy-MM-dd HH:mm:ss
        // yyyy-MM-dd
        // yyyy/MM/dd  yyyy年MM月dd日
        // 时间戳  124541245
        if(source.matches("\\d+")){
            long time = Long.parseLong(source);
            return new Timestamp(time);
        } else if(source.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){
            try {
                Date date = YYYYMMDD.parse(source);
                return new Timestamp(date.getTime());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else if(source.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}")){
            try {
                Date date = YYYYMMDDHHMMSS.parse(source);
                return new Timestamp(date.getTime());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new IllegalArgumentException("时间格式错误:" + source);
        }
    }
}
